package hwOne2;

import edu.princeton.cs.algs4.StdOut;

import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

/**
 * 1.2.11 1.2.12
 */
public class SmartDate {
    private final int month;
    private final int day;
    private final int year;

    public SmartDate(int m, int d, int y) {
        if (!isValidDate(m, d, y)) {
            throw new IllegalArgumentException("Invalid date: " + m + "/" + d + "/" + y);
        }
        month = m;
        day = d;
        year = y;
    }
    // 验证日期是否合法
    private boolean isValidDate(int m, int d, int y) {
        if (m < 1 || m > 12) return false; // 月份必须在 1 到 12 之间
        if (d < 1 || d > daysInMonth(m, y)) return false; // 天数必须在合法范围内
        return true;
    }
    private int daysInMonth(int m, int y) {
        switch (m) {
            case 1: case 3: case 5: case 7: case 8: case 10: case 12:
                return 31;
            case 4: case 6: case 9: case 11:
                return 30;
            case 2:
                return isLeapYear(y) ? 29 : 28;
            default:
                return 0; // 不可能到达这里
        }
    }
    // 判断是否是闰年
    private boolean isLeapYear(int y) {
        return (y % 4 == 0 && y % 100 != 0) || (y % 400 == 0);
    }

    public int month() {
        return month;
    }

    public int day() {
        return day;
    }

    public String dayOfTheWeek() {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        String current = toString();
        LocalDate date = LocalDate.parse(current, formatter);

        // 获取该日期是周几
        DayOfWeek dayOfWeek = date.getDayOfWeek();

        // 打印周几 (英文)
        int day = dayOfWeek.getValue();
        String[] camel = { "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"};
        return camel[day - 1];
    }

    public int year() {
        return year;
    }

    public String toString() {
        return year() + "-" + month() + "-" + day();
    }

    public boolean equals(Object x) {
        if (this == x) return true;
        if (x == null) return false;
        if (this.getClass() != x.getClass()) return false;
        SmartDate that = (SmartDate) x;
        if (this.day != that.day) return false;
        if (this.month != that.month) return false;
        if (this.year != that.year) return false;
        return true;
    }

    public static void main(String[] args) {
        int month = 11;
        int day = 18;
        int year = 2001;
        SmartDate date = new SmartDate(month, day, year);
        StdOut.println("Date: " + date);
        StdOut.println("week: " + date.dayOfTheWeek());
    }
}